package com.example.excel.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.example.excel.data.LongRentCarDto;
import com.example.excel.data.LongRentCarFailedDto;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;

import java.util.List;
import java.util.StringJoiner;
import java.util.function.Function;

/**
 * @author Aaron
 * @since 2021/7/16 11:21
 * <p>描述：</p>
 */
public class LongRentCarListener extends AnalysisEventListener<LongRentCarDto> {
    public static final Logger LOGGER = LoggerFactory.getLogger(LongRentCarListener.class);

    /**
     * 正常导入数据集合
     */
    private final List<LongRentCarDto> importTotalData;
    /**
     * 导入失败数据集合
     */
    private final List<LongRentCarFailedDto> importFailedList;
    /**
     * 校验数据
     */
    private final Function<LongRentCarDto, String> function;

    public LongRentCarListener(List<LongRentCarDto> importTotalData,
                               List<LongRentCarFailedDto> importFailedList,
                               Function<LongRentCarDto, String> function) {
        this.importTotalData = importTotalData;
        this.importFailedList = importFailedList;
        this.function = function;
    }

    @Override
    public void invoke(LongRentCarDto longRentCarDto, AnalysisContext context) {
        LOGGER.debug("【长租车】获取导入数据：{}", longRentCarDto);

        // 未通过校验数据，存放到失败集合中，最后导出
        String result = this.function.apply(longRentCarDto);

        if (StringUtils.isNotBlank(result)) {
            LongRentCarFailedDto longRentCarFailedDto = new LongRentCarFailedDto();
            BeanUtils.copyProperties(longRentCarDto, longRentCarFailedDto);
            longRentCarFailedDto.setErrField(new StringJoiner("_")
                    .add(longRentCarDto.getParkName())
                    .add(longRentCarDto.getCarNum())
                    .add(longRentCarDto.getVehicleType())
                    .add(result).toString());
            LOGGER.info("【长租车】校验失败数据：{}", longRentCarFailedDto);
            importFailedList.add(longRentCarFailedDto);
            return;
        }

        importTotalData.add(longRentCarDto);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        LOGGER.debug("所有数据解析完毕");
    }

}
